package com.putable.cgw.game;

import com.putable.cgw.game.member.Member;

/**
 * 
 * @author Todd
 *
 */
public class Gang {

	private int size;

	private Member first, last;

	/**
	 * Adds a Member to the back of the Gang
	 * 
	 * @param m
	 *            The Member to be added
	 */
	public void add(Member m) {
		if (m == null)
			throw new NullPointerException("Can not add null Member");
		if (last == null) {
			first = m;
			m.setUpChain(null);
		} else {
			m.setUpChain(last);
			last.setDownChain(m);
		}
		m.setDownChain(null);
		last = m;
		size++;
	}

	/**
	 * Deletes a Member from the Gang
	 * 
	 * @param m
	 *            Member to be deleted from the Gang
	 */
	public void delete(Member m) {
		if (m == null)
			throw new NullPointerException("Can not delete null Member");//Replace with error once errors set up
		if ((m.getUpChain() == null && m.getDownChain() == null && !(m == first && m == last)))
			throw new NullPointerException("That Member is not in line");
		// Sets the Member in front to be in front of the Member behind and vice-versa
		if (m.getUpChain() != null)
			m.getUpChain().setDownChain(m.getDownChain());
		if (m.getDownChain() != null)
			m.getDownChain().setUpChain(m.getUpChain());
		// If it is the only Member in the gang set the list to be empty
		if (m == first && m == last)
			first = last = null;
		// Decrement size of list
		if (size >= 0) size--;
	}

	public Member getFirst() {
		return first;
	}

	public int getSize() {
		return size;
	}

	public boolean isEmpty() {
		if (first == null)
			return true;
		return false;
	}
	
	/**
	 * @return the size of the current gang.
	 */
	public int size(){
		return size;
	}

	/**
	 * O(n) method that looks for Member m
	 * 
	 * @param m
	 *            The Member we are looking for
	 * @return whether or not we found m
	 */
	public boolean contains(Member m) {
		return recursiveContains(m, first);
	}

	private boolean recursiveContains(Member m, Member current) {
		if (current == null)
			return false;
		if (m == current)
			return true;
		return recursiveContains(m, current.getDownChain());
	}

}
